package dao.entity;

import java.util.List;

import javax.persistence.EntityManager;

import org.hibernate.criterion.Restrictions;

import model.NguoiDung;
import dao.AbstractDAO;
import dao.DatabaseConnector;

public class NguoiDungDAO extends AbstractDAO<NguoiDung, Integer> {

	public NguoiDungDAO() {
		super(NguoiDung.class);
	}

	public static boolean checkLogin(NguoiDung nguoiDung) {
		NguoiDungDAO nguoiDungDAO = new NguoiDungDAO();
		List<NguoiDung> list = nguoiDungDAO.selectAll();
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getEmail().equals(nguoiDung.getEmail())
					|| list.get(i).getPassWord()
							.equals(nguoiDung.getPassWord())) {
				return true;
			}
		}
		return false;
	}

	public static boolean checkUser(String email) {
		NguoiDungDAO nguoiDungDAO = new NguoiDungDAO();
		List<NguoiDung> list = nguoiDungDAO.selectAll();
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getEmail().equals(email)) {
				return true;
			}
		}
		return false;
	}

	public static NguoiDung getUser(String email) {
		NguoiDung nguoiDung = new NguoiDung();
		NguoiDungDAO dao = new NguoiDungDAO();
		List<NguoiDung> list = dao.findByCriteria(Restrictions.eq("email",
				email));
		nguoiDung.setTenNguoiDung(list.get(0).getTenNguoiDung());
		nguoiDung.setCapDo(list.get(0).getCapDo());
		nguoiDung.setPassWord(list.get(0).getPassWord());
		nguoiDung.setGioiTinh(list.get(0).isGioiTinh());
		nguoiDung.setDiaChi(list.get(0).getDiaChi());
		nguoiDung.setSoDienThoai(list.get(0).getSoDienThoai());
		return nguoiDung;
	}

	public void changePass(NguoiDung user) {
		EntityManager entityManager = DatabaseConnector.getEntityManager();
		NguoiDung nguoiDung = entityManager.find(NguoiDung.class,
				user.getId_NguoiDung());
		try {
			entityManager.getTransaction().begin();
			nguoiDung.setPassWord(user.getPassWord());
			entityManager.getTransaction().commit();
		} catch (Exception e) {
			entityManager.getTransaction().rollback();
		}
	}

	public void changeInfoUser(NguoiDung user) {
		EntityManager entityManager = DatabaseConnector.getEntityManager();
		NguoiDung nguoiDung = entityManager.find(NguoiDung.class,
				user.getId_NguoiDung());
		try {
			entityManager.getTransaction().begin();
			nguoiDung.setTenNguoiDung(user.getTenNguoiDung());
			nguoiDung.setDiaChi(user.getDiaChi());
			nguoiDung.setGioiTinh(user.isGioiTinh());
			nguoiDung.setSoDienThoai(user.getSoDienThoai());
			nguoiDung.setNgaySinh(user.getNgaySinh());
			entityManager.getTransaction().commit();
		} catch (Exception e) {
			entityManager.getTransaction().rollback();
		}
	}
}
